#include "fileobject.h"

#include <QFile>
#include <QFileDialog>

#include <QTextStream>
#include <qDebug>
FileObject::FileObject(QObject *parent) : QObject(parent) {}

QString FileObject::read() {
  m_source = QFileDialog::getOpenFileName(nullptr, tr("Open File"),
                                          NULL, // ".",
                                          tr("*.bin"));

  QFile file(m_source);
  if (file.open(QIODevice::ReadOnly)) {
    m_content = file.readAll();
    m_size = m_content.size();
    file.close();
  }

  return m_source;
}

QByteArray FileObject::readByte() {

  m_source = QFileDialog::getOpenFileName(nullptr, tr("Open File"),
                                          NULL, // ".",
                                          tr("*.bin"));
  QFile file(m_source);
  qDebug() << "open file " << m_source;
  if (file.open(QIODevice::ReadOnly)) {
    m_content = file.readAll();
    m_size = m_content.size();
    file.close();
  }
  return m_content;
}

bool FileObject::write(const QString &data) {
  QFile file(m_source);
  qDebug() << "open file " << m_source;
  if (file.open(QFile::WriteOnly | QFile::Truncate)) {
    QTextStream out(&file);
    out << data;
    file.close();
    return true;
  } else {
    return false;
  }
}

void FileObject::setSource(const QString &source) { m_source = source; }

int FileObject::size() const { return m_size; }

QByteArray FileObject::content() const { return m_content; }
